// import { initAllDb } from "@/dao/config/init"
import { initTables, execTables } from "@/dao/master/zsctask"

const { ipcRenderer } = require("electron")
const fs = require("fs")
const path = require("path")

// 工具函数
// function getRandom() { return String(Math.random()).slice(2, 12) }

async function choosedir() {
    // 打开文件目录
    return new Promise((resolve) => {
        ipcRenderer.once('note_choosedir_rep', (event, arg) => {
            arg.length > 0 ? resolve(arg[0]) : resolve()
        })
        ipcRenderer.send("note_choosedir_msg")
    })
}

// 返回文件列表
/* 
function walkDirList(currentDirPath, callback) {
    const path = require('path');
    fs.readdirSync(currentDirPath).forEach(function (name) {
        var filePath = path.join(currentDirPath, name);
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
            callback(filePath, stat);
        } else if (stat.isDirectory()) {
            walkDirList(filePath, callback);
        }
    });
}
*/

function walkDirTree(dir) {
    let dirtree = {
        name: path.basename(dir),
        filepath: dir,
        isdir: true,
        children: [],
    }
    fs.readdirSync(dir).forEach(function(filename) {
        const dirpath = dir + "\\" + filename
        const stat = fs.statSync(dirpath)
        if (stat && stat.isDirectory()) {
            // children = children.concat(walkDirTree(path))
            // if( "children" in dirtree ) dirtree["children"].push(walkDirTree(path))
            dirtree.children.push(walkDirTree(dirpath))
        } else {
            // dirtree.push(path)
            const file = {
                name: path.basename(dirpath),
                file: getFileType(dirpath),
                filepath: dirpath,
            }
            dirtree.children.push(file)
        }
    })
    return dirtree
}


// 获取文件后缀名
function getFileType(dir) {
    const file = path.basename(dir)
    const index = file.lastIndexOf(".")
    if (index == -1) return "txt"
    else return file.substr(index + 1).toLowerCase()
}

export async function openDir() {
    let filepath = await choosedir()
    if (!filepath) return
    else return new Promise((resolve) => {
        const dirtree = walkDirTree(filepath)
        console.log(dirtree)
        resolve(dirtree)
    })
}

export async function openDirPath(path) {
    return new Promise((resolve) => {
        const dirtree = walkDirTree(path)
        console.log(dirtree)
        resolve(dirtree)
    })
}

export async function newFile(path, filename) {
    const dirpath = path + "\\" + filename
    if (fs.existsSync(dirpath)) {
        return
    }
    return new Promise((resolve) => {
        fs.writeFile(dirpath, "\n", function() {
            resolve()
        })
    })
}

export async function newFolder(path, filename) {
    const dirpath = path + "\\" + filename
    if (fs.existsSync(dirpath)) {
        return
    }
    return new Promise((resolve) => {
        fs.mkdir(dirpath, '0777', function() {
            resolve()
        })
    })
}

export function deleteall(path) {
    let files = [];
    if (fs.existsSync(path)) {
        const stat = fs.statSync(path)
        if (!stat.isDirectory()) {
            fs.rmSync(path);
        } else {
            files = fs.readdirSync(path);
            files.forEach(function(file) {
                let curPath = path + "\\" + file;
                console.log(curPath);
                if (fs.statSync(curPath).isDirectory()) {
                    deleteall(curPath);
                } else {
                    fs.unlinkSync(curPath);
                }
            });
            fs.rmdirSync(path);
        }
    }
}

export async function initdb() {
    await initTables()
    await execTables()
}